import React, {Component} from 'react';
import Vditor from 'vditor'
import "vditor/src/assets/scss/index.scss";
import {AliyunOss} from '@/services/alioss'
import {seedOss} from "@/components/VditorMd/services";
import {nanoid} from "nanoid";

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editValue: props.value
    };
  }

  componentDidMount = () => {
    // 组件挂载完成之后调用 注意一定要在组件挂载完成之后调用 否则会找不到注入的DOM
    this.createVidtor({ value: this.state.editValue,props:this.props });
  }

  // 创建编辑器 下面会详解
  createVidtor = params => {
    let { value,props } = params;
    // value = value ? value : " ";
    let that = this;
    const vditor = new Vditor("vditor", {
      height: 400,
      mode: "ir", // 及时渲染模式
      toolbar: [
        "emoji",
        "headings",
        "bold",
        "italic",
        "strike",
        "link",
        "|",
        "list",
        "ordered-list",
        "check",
        "outdent",
        "indent",
        "|",
        "quote",
        "line",
        "code",
        "inline-code",
        "insert-before",
        "insert-after",
        "|",
        "upload",
        "table",
        "|",
        "undo",
        "redo",
        "|",
        "fullscreen",
        "edit-mode",
        {
          name: "more",
          toolbar: [
            "both",
            "code-theme",
            "content-theme",
            "export",
            "outline",
            "preview",
            "devtools",
            "info",
            "help"
          ]
        },
        "|",
        {
          hotkey: "⌘-S",
          name: "save",
          tipPosition: "s",
          tip: "保存",
          className: "right",
          icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/save.svg'/>`,
          click() {
            that.saveDoc();
          }
        },
        {
          hotkey: "",
          name: "publish",
          tipPosition: "s",
          tip: "发布文章",
          className: "right",
          icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/publish.svg'/>`,
          click() {
            that.publishDoc();
          }
        },
      ],
      after() {
        vditor.setValue(value);
      },
      blur(value) {
        const htmlValue = that.vditor.getHTML()
        props.inputData(value,htmlValue)
        console.log('离开执行')
      },
      input(value, previewElement) {
        const htmlValue = that.vditor.getHTML()
        props.inputData(value,htmlValue)
      },
      value,
      placeholder : '请输入文章内容,支持MD语法',
      upload: {
        accept: "image/*",
        multiple: false,
        filename(name) {
          return name
            .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
            .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
            .replace("/\\s/g", "");
        },
        handler(files) {
          function callback(path) {
            let name = files[0] && files[0].name;
            let succFileText = "";
            if (vditor && vditor.vditor.currentMode === "wysiwyg") {
              succFileText += `\n <img alt=${name} src="${path}">`;
            } else {
              succFileText += ` \n![${name}](${path})`;
            }
            document.execCommand("insertHTML", false, succFileText);
          }
          that.handleImageUpload(files, callback);
        },
        url(files) {
          that.handleImageUpload(files);
        }
      },
    });

    // 此接口里面调用的是自己的图片上传 业务方自行实现
    this.handleImageUpload = async (file, callback) => {
      console.log(file)
      const reader = new FileReader();

      const formdata = new FormData();

      // 发送请求 获取Oss token
      const OSSData = await AliyunOss();
      console.log(OSSData)
      const newName = nanoid() + Math.random(1,99999) + file[0].name
      formdata.append('key',newName);
      formdata.append('OSSAccessKeyId',OSSData.accessid);
      formdata.append('policy',OSSData.policy);
      formdata.append('Signature',OSSData.signature);
      formdata.append('success_action_status', 200)
      formdata.append("file", file[0]);
      reader.onload = async  () => {
        // 当异步上传获取图片地址后，执行callback回调（参数为imageUrl字符串），即可将图片地址写入markdown

          // 写入上传
          const url = OSSData.host;
          await seedOss(url,formdata)


           let imgurl = OSSData.host + newName;
            callback(imgurl);
      };
      reader.readAsDataURL(file[0]);
    };

    this.vditor = vditor;
    return vditor;
  };

  render() {
    return (
      <div>
        <div className="editorWrap">
          <div id="vditor" />
        </div>
      </div>
    );
  }
}

export default Index;
